package com.taoyibao.hongcanting.ui.home.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.taoyibao.hongcanting.R;
import com.taoyibao.hongcanting.base.activity.BaseActivityPresenter;
import com.taoyibao.hongcanting.cache.SpUtils;
import com.taoyibao.hongcanting.constant.ApiConstant;
import com.taoyibao.hongcanting.constant.CodeConstant;
import com.taoyibao.hongcanting.constant.NetCode;
import com.taoyibao.hongcanting.event.EventQRCode;
import com.taoyibao.hongcanting.event.EventSubmitSuccess;
import com.taoyibao.hongcanting.http.DefaultTransformer;
import com.taoyibao.hongcanting.http.JsonApiWrapper;
import com.taoyibao.hongcanting.http.ProgressSubscriber;
import com.taoyibao.hongcanting.model.CompanyBaseModel;
import com.taoyibao.hongcanting.model.DishModel;
import com.taoyibao.hongcanting.model.FoodTypeModel;
import com.taoyibao.hongcanting.model.OrderEatTypeMode;
import com.taoyibao.hongcanting.model.OrderInfoModel;
import com.taoyibao.hongcanting.model.OrderModel;
import com.taoyibao.hongcanting.model.OrderPageModel;
import com.taoyibao.hongcanting.model.ResultStringModel;
import com.taoyibao.hongcanting.model.SanFangBaseModel;
import com.taoyibao.hongcanting.model.ShoppingCartModel;
import com.taoyibao.hongcanting.ui.home.delegate.SubmitOrdersDelegate;
import com.taoyibao.hongcanting.ui.mine.activity.WaitPayActivity;
import com.taoyibao.hongcanting.utils.CodeUtils;
import com.taoyibao.hongcanting.utils.DataUtils;
import com.taoyibao.hongcanting.utils.LogUtils;
import com.taoyibao.hongcanting.utils.ToastUtils;
import com.taoyibao.hongcanting.utils.permission.MPermission;
import com.taoyibao.hongcanting.utils.permission.OnMPermissionDenied;
import com.taoyibao.hongcanting.utils.permission.OnMPermissionGranted;
import com.taoyibao.hongcanting.utils.permission.OnMPermissionNeverAskAgain;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author TangAnna
 * @description: 提交订单
 * @date :${DATA} 16:09
 */
public class SubmitOrdersActivity extends BaseActivityPresenter<SubmitOrdersDelegate> implements View.OnClickListener {

    private double totalMoney;
    private double discountMoeny;
    private List<FoodTypeModel> mInfo;
    private String mOrderId;//订单ID
    //未支付订单的备注
    private String mOrderRemark;
    private String mTotalRemark;//总共的拼接之后的备注
    /**
     * 用于区分是否是外带订单  true 外带订单  false 非外带订单
     */
    private boolean isWaidai = false;

    private static final int REQUEST_CODE_PERMISSION = 102;
    //需要申请的权限的数组
    private String[] mPermissions = {Manifest.permission.CAMERA};
    private static final int ISADD = 1;//加单
    private static final int SUBMIT = 0;//提交订单
    private String mDeskId;//堂食的座位号


    @Override
    protected Class<SubmitOrdersDelegate> getDelegateClass() {
        return SubmitOrdersDelegate.class;
    }

    /**
     * @param context
     * @param seatNub 用户的桌号  没扫码的话传空值
     */
    public static void open(Context context, String seatNub) {
        Intent intent = new Intent(context, SubmitOrdersActivity.class);
        intent.putExtra(CodeConstant.SEAT_NUMBER, seatNub);
        context.startActivity(intent);
    }

    @Override
    protected void bindEvenListener() {
        super.bindEvenListener();
        EventBus.getDefault().register(this);
        viewDelegate.get(R.id.btn_submit_order_submit).setOnClickListener(this);
        getShoppingCartData();
        getOrderData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 扫描桌位更新页面状态
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventSeatId(EventQRCode event) {
        if (!TextUtils.isEmpty(event.seatId)) {
            OrderInfoModel orderInfoModel = new OrderInfoModel();
            orderInfoModel.order_deskname = event.seatName;
            orderInfoModel.order_deskid = event.seatId;
            viewDelegate.setSeatUI(orderInfoModel);
        }
    }

    /**
     * 网络请求购物车数据
     */
    public void getShoppingCartData() {
        JsonApiWrapper.getApiService().cartInfo(SpUtils.getToken(), SpUtils.getMemberId())
                .compose(new DefaultTransformer<CompanyBaseModel<List<ShoppingCartModel>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<ShoppingCartModel>>>(this, true) {
                    @Override
                    public void onNext(CompanyBaseModel<List<ShoppingCartModel>> shoppingCartModel) {
                        if (shoppingCartModel.code == NetCode.HTTP_200) {
                            mInfo = shoppingCartModel.data.get(0).info;
                            totalMoney = shoppingCartModel.data.get(0).discount_price;
                            discountMoeny = (shoppingCartModel.data.get(0).origin_price - shoppingCartModel.data.get(0).discount_price);
                            viewDelegate.setListData(shoppingCartModel.data);
                            viewDelegate.setDataView();
                        } else {
                            viewDelegate.setErrorView(new Throwable());
                            super.onNext(shoppingCartModel);
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_submit_order_submit://提交订单
                getOrder();//先判断是否有未支付订单
                break;
        }
    }


    /**
     * 判断是否有未支付订单
     */
    public void getOrder() {
        JsonApiWrapper.getApiService().userOrders(SpUtils.getToken(), SpUtils.getMemberId(), CodeConstant.ORDER_STATUS_NOPAY, 1, 1000)
                .compose(new DefaultTransformer<CompanyBaseModel<OrderPageModel>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<OrderPageModel>>(this, true) {
                    @Override
                    public void onNext(CompanyBaseModel<OrderPageModel> orderPageModel) {
                        if (orderPageModel.code == NetCode.HTTP_200) {
                            if (orderPageModel.data != null && orderPageModel.data != null &&
                                    orderPageModel.data.orders_info != null && orderPageModel.data.orders_info.size() > 0) {//有未支付订单
                                mOrderId = orderPageModel.data.orders_info.get(0).order_id;
                                submitOrder(ISADD);
                            } else {//没有未支付订单
                                submitOrder(SUBMIT);
                            }
                        } else {
                            submitOrder(SUBMIT);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        submitOrder(SUBMIT);
                    }
                });
    }

    /**
     * 获取未支付订单信息
     */
    public void getOrderData() {
        JsonApiWrapper.getApiService().userOrders(SpUtils.getToken(), SpUtils.getMemberId(), CodeConstant.ORDER_STATUS_NOPAY, 1, 1000)
                .compose(new DefaultTransformer<CompanyBaseModel<OrderPageModel>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<OrderPageModel>>(this, true) {
                    @Override
                    public void onNext(CompanyBaseModel<OrderPageModel> orderPageModel) {
                        if (orderPageModel.code == NetCode.HTTP_200 && orderPageModel.data != null
                                && orderPageModel.data.orders_info != null && orderPageModel.data.orders_info.size() > 0) {
                            OrderModel orderModel = orderPageModel.data.orders_info.get(0);
                            if (orderModel.order_paystatus == CodeConstant.ORDER_STATUS_NOPAY) {//有未支付订单
                                getEatType(orderModel.order_id);
                            } else {
                                viewDelegate.setSeatUI(null);
                            }
                        } else {
                            super.onNext(orderPageModel);
                            viewDelegate.setSeatUI(null);
                        }
                    }
                });
    }

    /**
     * 获取桌位信息判断未支付订单时外带还是堂食
     */
    public void getEatType(final String orderId) {
        JsonApiWrapper.getApiService().orderEatType(SpUtils.getToken(), orderId, CodeConstant.SELECT_ORDERID_EAT_TYPE, null, null)
                .compose(new DefaultTransformer<CompanyBaseModel<List<OrderEatTypeMode>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<OrderEatTypeMode>>>(this, false) {
                    @Override
                    public void onNext(CompanyBaseModel<List<OrderEatTypeMode>> companyBaseModel) {
                        if (companyBaseModel.code == NetCode.HTTP_200 && companyBaseModel.data != null && companyBaseModel.data.size() > 0) {
                            OrderEatTypeMode orderEatTypeMode = companyBaseModel.data.get(0);
                            if (orderEatTypeMode.eatType == CodeConstant.EAT_TYPE_TANGSHI) {//堂食
                                mDeskId = companyBaseModel.data.get(0).deskId;
                                getFoodOrderInfo(companyBaseModel.data.get(0).deskId);
                            } else if (orderEatTypeMode.eatType == CodeConstant.EAT_TYPE_WAIDAI) {//外带
                                getTakeoutOrderInfo(orderId);
                            }
                        }
                    }
                });
    }

    /**
     * 获取堂食订单详情
     */
    public void getFoodOrderInfo(String deskId) {
        JsonApiWrapper.getApiService().getDeskOrderInfo(ApiConstant.MASTER_ID, DataUtils.getKey(), ApiConstant.BRANCH_ID, deskId)
                .compose(new DefaultTransformer<SanFangBaseModel<OrderInfoModel>>())
                .subscribe(new ProgressSubscriber<SanFangBaseModel<OrderInfoModel>>(this, true) {
                    @Override
                    public void onNext(SanFangBaseModel<OrderInfoModel> sanFangBaseModel) {
                        if (sanFangBaseModel.Code == NetCode.HTTP_200 && sanFangBaseModel.Data != null) {

                            parserOrderInfo(sanFangBaseModel.Data);
                        } else {
                            viewDelegate.setSeatUI(null);
                        }
                    }
                });
    }

    /**
     * 获取外带的订单信息
     *
     * @param orderId
     */
    public void getTakeoutOrderInfo(String orderId) {
        JsonApiWrapper.getApiService().getOrderInfo(ApiConstant.MASTER_ID, DataUtils.getKey(), ApiConstant.BRANCH_ID, SpUtils.getMemberId(), orderId)
                .compose(new DefaultTransformer<SanFangBaseModel<OrderInfoModel>>())
                .subscribe(new ProgressSubscriber<SanFangBaseModel<OrderInfoModel>>(this, false) {
                    @Override
                    public void onNext(SanFangBaseModel<OrderInfoModel> result) {
                        if (result.Code == NetCode.HTTP_200 && result.Data != null) {
                            parserOrderInfo(result.Data);
                        } else {
                            viewDelegate.setSeatUI(null);
                        }
                    }
                });
    }

    /**
     * 根据订单信息解析数据并设置数据
     */
    public void parserOrderInfo(OrderInfoModel data) {
        mOrderRemark = data.order_remark;//获取出上一个订单的备注
        viewDelegate.setSeatUI(data);
        if (!TextUtils.isEmpty(data.order_deskid)) {//标记是否是外带订单
            isWaidai = false;
        } else {
            isWaidai = true;
        }
        //餐厅名称
        if (!TextUtils.isEmpty(data.order_companyname)) {
            ((TextView) viewDelegate.get(R.id.tv_submit_order_companyname)).setText(data.order_companyname);
        } else {
            ((TextView) viewDelegate.get(R.id.tv_submit_order_companyname)).setText(CodeUtils.getIdString(R.string.string_restaurantName));
        }
    }

    /**
     * 获取编码后的数据
     *
     * @return
     */
    public String getUrlDish() {
        List<DishModel> dishModels = new ArrayList<>();
        for (int i = 0; i < mInfo.size(); i++) {
            List<DishModel> children = mInfo.get(i).children;
            for (int j = 0; j < children.size(); j++) {
                children.get(j).dish_practicetaste = children.get(j).getDish_practicetaste();
                children.get(j).dish_price = children.get(j).dish_discount_price;
            }
            dishModels.addAll(children);
        }
        String json = new Gson().toJson(dishModels);
        LogUtils.dNormal("URL编码前", json);
        try {
            String encode = URLEncoder.encode(json, "UTF-8");
            LogUtils.dNormal("URL编码后", encode);
            return encode;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 提交订单
     */
    public void submitOrder(final int isAdd) {
        if (!TextUtils.isEmpty(SpUtils.getOtherSeatName()) || !viewDelegate.isNeedQRCode) {//不需要扫码
            //桌位信息
            String deskId = null;
            if (!TextUtils.isEmpty(SpUtils.getSeatId())) {
                deskId = SpUtils.getSeatId();
            }
            //备注信息
            String remark = viewDelegate.getRemark();
            if (isAdd == ISADD && !TextUtils.isEmpty(mOrderRemark) && !TextUtils.equals(mOrderRemark, "0")) {//拼接加单的备注信息
                remark = remark + mOrderRemark;
            }
            //拼接赠送的备注信息
            if (!TextUtils.isEmpty(SpUtils.getOtherSeatId())) {
                String seat = CodeConstant.ZENG_YU + SpUtils.getOtherSeatId() + CodeConstant.ZHUO_HAO;
                remark = remark + CodeConstant.ZENG_SONG + getOtherDish() + seat;
            }
            //最终得到的备注，加单接口也是用这个参数
            mTotalRemark = remark;
            if (isAdd == SUBMIT) {//提交订单时判断就餐方式使用此方法判断  加单不判断
                if (!TextUtils.isEmpty(deskId)) {//标记是否是外带订单
                    isWaidai = false;
                } else {
                    isWaidai = true;
                }
            }
            JsonApiWrapper.getApiService().submitOrder(ApiConstant.MASTER_ID, DataUtils.getKey(), ApiConstant.BRANCH_ID,
                    1, deskId,
                    viewDelegate.getEatWay(), SpUtils.getUserPhone(), SpUtils.getUserNub(),
                    getUrlDish(), totalMoney, discountMoeny, mTotalRemark, isAdd)
                    .compose(new DefaultTransformer<SanFangBaseModel<ResultStringModel>>())
                    .subscribe(new ProgressSubscriber<SanFangBaseModel<ResultStringModel>>(this, true) {
                        @Override
                        public void onNext(SanFangBaseModel<ResultStringModel> commonModel) {
                            if (commonModel.Code == NetCode.HTTP_200) {//提交成功
                                if (isAdd == SUBMIT) {
                                    //提交订单成功
                                    mOrderId = commonModel.Data.order_id;
                                    ToastUtils.showToast("提交成功");
                                    addDeskStatus();
                                    cartClear();
                                } else if (isAdd == ISADD) {
                                    addDish();
                                }
                            } else {
                                super.onNext(commonModel);
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                            LogUtils.dNormal("提交订单异常", "ffff");
                        }
                    });
        } else {//扫码
            requestBasicPermission(mPermissions, REQUEST_CODE_PERMISSION);
        }
    }

    /**
     * 添加订单的就餐方式
     */
    public void addDeskStatus() {
        //桌位信息
        String deskId = null;
        if (!TextUtils.isEmpty(SpUtils.getSeatId())) {
            deskId = SpUtils.getSeatId();
        }
        LogUtils.dNormal("提交订单之前的座位ID", deskId);
        JsonApiWrapper.getApiService().orderEatType(SpUtils.getToken(), mOrderId, CodeConstant.ADD_ORDERID_EAT_TYPE, viewDelegate.getEatWay(), deskId)
                .compose(new DefaultTransformer<CompanyBaseModel<List<OrderEatTypeMode>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<OrderEatTypeMode>>>(this, false) {
                    @Override
                    public void onNext(CompanyBaseModel<List<OrderEatTypeMode>> companyBaseModel) {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                });
    }

    /**
     * 拼接要赠送的菜品信息
     *
     * @return
     */
    public String getOtherDish() {
        List<DishModel> dishModels = new ArrayList<>();
        for (int i = 0; i < mInfo.size(); i++) {
            List<DishModel> children = mInfo.get(i).children;
            for (int j = 0; j < children.size(); j++) {
                children.get(j).dish_practicetaste = children.get(j).getDish_practicetaste();
                children.get(j).dish_price = children.get(j).dish_discount_price;
            }
            dishModels.addAll(children);
        }
        String otherDish = null;
        for (int i = 0; i < dishModels.size(); i++) {
            DishModel dishModel = dishModels.get(i);
            String replace = dishModel.dish_practicetaste.replace("0", "");

            if (!TextUtils.isEmpty(replace) && !TextUtils.equals(replace, ",")) {//有口味和做法
                otherDish = dishModel.dish_name + "  x" + dishModel.dish_count + "  " + dishModel.dish_practicetaste;
            } else {
                otherDish = dishModel.dish_name + "  x" + dishModel.dish_count;
            }
        }
        return otherDish;
    }

    /**
     * 加菜操作
     */
    public void addDish() {
        //桌位信息
        String deskId = null;
        if (!TextUtils.isEmpty(mDeskId)) {
            deskId = mDeskId;
        } else if (!TextUtils.isEmpty(SpUtils.getSeatId())) {
            deskId = SpUtils.getSeatId();
        }
        //备注信息
        String remark = viewDelegate.getRemark();
        if (!TextUtils.isEmpty(mOrderRemark) && !TextUtils.equals(mOrderRemark, "0")) {//拼接加单的备注信息
            remark = remark + mOrderRemark;
        }
        //拼接赠送的备注信息
        if (!TextUtils.isEmpty(SpUtils.getOtherSeatId())) {
            String seat = CodeConstant.ZENG_YU + SpUtils.getOtherSeatId() + CodeConstant.ZHUO_HAO;
            remark = remark + CodeConstant.ZENG_SONG + getOtherDish() + seat;
        }
        //最终得到的备注，加单接口也是用这个参数
        mTotalRemark = remark;

        JsonApiWrapper.getApiService().submitOrder(ApiConstant.MASTER_ID, DataUtils.getKey(), ApiConstant.BRANCH_ID,
                1, deskId,
                viewDelegate.getEatWay(), SpUtils.getUserPhone(), SpUtils.getUserNub(),
                getUrlDish(), totalMoney, discountMoeny, mTotalRemark, ISADD)
                .compose(new DefaultTransformer<SanFangBaseModel<ResultStringModel>>())
                .subscribe(new ProgressSubscriber<SanFangBaseModel<ResultStringModel>>(this, true) {
                    @Override
                    public void onNext(SanFangBaseModel<ResultStringModel> commonModel) {
                        if (commonModel.Code == NetCode.HTTP_200) {
                            cartClear();
                            ToastUtils.showToast("加菜成功");
                        } else {
                            super.onNext(commonModel);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        LogUtils.dNormal("提交订单异常", "ffff");
                    }
                });


//        JsonApiWrapper.getApiService().addDish(ApiConstant.MASTER_ID, DataUtils.getKey(), ApiConstant.BRANCH_ID,
//                SpUtils.getMemberId(), 1, mOrderId, getUrlDish(),
//                totalMoney, discountMoeny, mTotalRemark)
//                .compose(new DefaultTransformer<SanFangBaseModel>())
//                .subscribe(new ProgressSubscriber<SanFangBaseModel>(this, true) {
//                    @Override
//                    public void onNext(SanFangBaseModel commonModel) {
//                        if (commonModel.Code == NetCode.HTTP_200) {
//                            cartClear();
//                            ToastUtils.showToast("加菜成功");
//                        } else {
//                            super.onNext(commonModel);
//                        }
//                    }
//                });
    }

    /**
     * 清空购物车
     */
    public void cartClear() {
        //赠送成功清除赠送的信息
        SpUtils.putOtherSeatName("");
        SpUtils.putOtherSeatId("");
        JsonApiWrapper.getApiService().cartClear(SpUtils.getToken(), SpUtils.getMemberId())
                .compose(new DefaultTransformer<CompanyBaseModel>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel>(this, false) {
                    @Override
                    public void onNext(CompanyBaseModel companyBaseModel) {

                    }
                });
        sendEvent();
    }

    /**
     * 购物车清空成功之后通知点餐页面刷新
     */
    public void sendEvent() {
        EventSubmitSuccess eventSubmitSuccess = new EventSubmitSuccess(true);
        EventBus.getDefault().post(eventSubmitSuccess);
        //页面跳转 判断是否是外带订单
        if (isWaidai) {
            PayActivity.open(SubmitOrdersActivity.this, mOrderId, SpUtils.getMemberId());
        } else {
            WaitPayActivity.open(SubmitOrdersActivity.this, mOrderId);
        }
        SpUtils.putSeatId("");
        SpUtils.putSeatName("");
        SpUtils.putUserNub(0);
        finish();
    }

    /**
     * 基本权限管理
     */
    private void requestBasicPermission(String[] permission, int requestCode) {
        MPermission.with(this)
                .addRequestCode(requestCode)
                .permissions(
                        permission
                ).request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    //同意
    @RequiresApi(api = Build.VERSION_CODES.M)
    @OnMPermissionGranted(REQUEST_CODE_PERMISSION)
    public void onBasicPermissionSuccess() {
        QRCodeActivity.open(this, CodeConstant.ACTIVITY_SOURCE_SUBMIT);
    }

    //拒绝
    @OnMPermissionDenied(REQUEST_CODE_PERMISSION)
    public void onBasicPermissionFailed() {
        ToastUtils.showToast(CodeUtils.getIdString(R.string.string_hintPermission));
    }

    //不再提醒
    @OnMPermissionNeverAskAgain(REQUEST_CODE_PERMISSION)
    public void onBasicPermissionNeverAskAgain() {
        ToastUtils.showToast(CodeUtils.getIdString(R.string.string_hintPermission));
    }
}
